<!DOCTYPE html>
<html lang="en">
	<head>
		<meta charset="UTF-8" />
		<meta name="viewport" content="width=device-width, initial-scale=1.0" />
		<meta http-equiv="X-UA-Compatible" content="ie=edge" />
		<link rel="stylesheet" href="/static/index.css" />
		<title>文件夹上传</title>
	</head>

	<body>
		<h4>文件夹上传</h4>
		<a href="/" style="color: crimson;">返回首页</a>
		<div id="uploadForm">
			<input type="file" webkitdirectory multiple />
			<button id="uploadBtn" type="button">upload</button>
			<p>
				<a href="/filelist" style="color: crimson;">查看文件列表</a>
			</p>
		</div>
		<!-- <form id="uploadForm" action="" method="post" enctype="multipart/form-data">
      <p>
        <input type="file" name="file" multiple webkitdirectory accept="*/*" />
        <input type="submit" value="提交" id="submit" />
      </p>
      <p>
        <a href="/filelist" style="color: crimson;">查看文件列表</a>
      </p>
    </form> -->
		<div class="pop">
			<div class="loader"></div>
		</div>
	</body>
	<script src="/static/jquery.js"></script>
	<script>
		$(function() {
			// $('#submit').click(function (event) {
			//   event.preventDefault()
			//   $('.pop').show()
			//   $.ajax({
			//     type: 'POST',
			//     url: '/uploads',
			//     processData: false,
			//     contentType: false,
			//     data: new FormData($('#uploadForm')[0]),
			//     success: function (data) {
			//       setTimeout(() => {
			//         $('.pop').hide()
			//       }, 600)
			//     },
			//     error: function (data) {
			//       alert('上传失败！')
			//     },
			//   })
			// })

			// return false

			var files = []
			$(document).ready(function() {
				$('input').change(function() {
					files = this.files
					console.log('files:', files)
				})
			})
			$('#uploadBtn').click(function() {
				event.preventDefault()
				$('.pop').show()
				let formData = new FormData()
				for (var i = 0; i < files.length; i++) {
					formData.append('file', files[i])
					const directory = directorySplice(
						files[i]['name'],
						files[i]['webkitRelativePath'],
					)
					console.log('directory::', directory);
					formData.append('directory', directory[0])
				}
				$.ajax({
					type: 'POST',
					url: '/uploads',
					processData: false,
					contentType: false,
					cache: false,
					data: formData,
					success: function(data) {
						setTimeout(() => {
							$('.pop').hide()
						}, 600)
					},
					error: function(data) {
						setTimeout(() => {
							$('.pop').hide()
						}, 600)
						// alert('上传失败！')
					},
				})
			})
		})

		function directorySplice(name, webkitRelativePath) {
			return webkitRelativePath.split(name)
		}
	</script>
</html>
